package com.ita.service.impl;

import static org.junit.Assert.assertEquals;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.activemq.filter.function.inListFunction;
import org.apache.commons.net.time.TimeUDPClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ita.annotation.ServiceLog;
import com.ita.controller.MyWsHandler;
import com.ita.dao.FoodDao;
import com.ita.dao.MUserDao;
import com.ita.dao.OrderDao;
import com.ita.dao.UserDao;
import com.ita.dto.OrderDto;
import com.ita.dto.OrderItemDto;
import com.ita.pojo.Food;
import com.ita.pojo.Order;
import com.ita.pojo.OrderItem;
import com.ita.service.OrderService;
import com.ita.util.Constant;
import com.ita.util.TimeUtil;
import com.ita.vo.OrderItemVo;

@Service(value="orderService")
public class OrderServiceImpl implements OrderService{

	@Resource(name = "userDao")
	private UserDao udao;
	
	@Resource(name = "orderDao")
	private OrderDao odao;
	
	@Resource(name = "foodDao")
	private FoodDao fdao;
	
	@Resource(name = "merchantDao")
	private MUserDao mdao;
	
	@Override
	@Transactional
	@ServiceLog(description="add order")
	public Order addOrder(OrderDto orderDto) {
		
		Order order = new Order();
		order.setcUser(udao.select(orderDto.getC_id()));
		order.setMerchant(mdao.getById(orderDto.getM_id()));
		double sum =0.0;
		List<OrderItemDto> items = orderDto.getOrderDetail();
		for(OrderItemDto item:items){
			Food food = fdao.select(item.getFoodId());
			OrderItem tmp = new OrderItem();
			tmp.setId(UUID.randomUUID().toString());
			tmp.setCount(item.getCount());
			tmp.setFood(food);
			tmp.setOrder(order);
			order.getOrderItemSet().add(tmp);
			sum += food.getPrice() * tmp.getCount();
		}
		
		order.setTotal(sum);
		order.setC_address(orderDto.getC_address());
		order.setState(Constant.ORDER_UNTREATED);
		order.setCreate_time(System.currentTimeMillis());
		
		
	
		return odao.add(order);

	}

	@Override
	@Transactional
	@ServiceLog(description="update state")
	public int updateState(String id, int state) {
		return odao.updateState(id, state);
	}

	@Override
	@ServiceLog(description="get order by m_id and state")
	public List<Order> getOrder(String m_id, int state) {
		
		return odao.findAllWithState(m_id, state);
	}

	@Override
	@ServiceLog(description="get order by m_id")
	public List<Order> getOrder(String m_id) {
		// TODO Auto-generated method stub
		return odao.findAll(m_id);
	}

	@Override
	@Transactional
	@ServiceLog(description="auto update state")
	public int autoUpdateState() {
		List<Order> orders =  odao.findAllNoState(Constant.ORDER_FINISH);
		
		Date cur_time = new Date();
		
		for(Order order:orders){
			if((cur_time.getTime()-order.getCreate_time())>86400){
				odao.updateState(order.getId(), Constant.ORDER_FINISH);
			}
		}
		
		return 0;
	}

}
